package game.gfx;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

public class SpriteUtil
{
    public static List<BufferedImage> readSprites(InputStream input, int size)
    {
     // load big image
        BufferedImage bimg = null;
        try
        {
            bimg = ImageIO.read(input);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e.getLocalizedMessage());
        }
        // get the tiles out of it
        int rows = bimg.getHeight() / size;
        int cols = bimg.getWidth() / size;
        List<BufferedImage> sprites = new ArrayList<BufferedImage>(rows * cols);
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                sprites.add(bimg.getSubimage(j * size, i * size, size, size));
            }
        }
        return sprites;
    }
    
    public static void writeSpritesToDisk(List<BufferedImage> sprites, File parent)
    {
        // write sprites to disc
        int count = 0;
        int maxLength = String.valueOf(sprites.size()).length();
        StringBuilder zeroString = new StringBuilder(maxLength);
        for (int i = 0; i < maxLength; i++)
        {
            zeroString.append("0");
        }
        for (BufferedImage bufferedImage : sprites)
        {
            String name = String.valueOf(count++);
            if (name.length() < maxLength)
            {
                name = zeroString.substring(name.length()) + name;
            }
            try
            {
                File t = new File(parent, name + ".png");
                t.mkdirs();
                ImageIO.write(bufferedImage, "png", t);
                System.out.println(t.getAbsolutePath() + " created");
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
